<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';

const $router = useRouter();
const $route = useRoute();
const searchHistory = ref<string[]>([]);
const searchValue = ref($route.query.keyword as string);
const onSearchClick = () => {
  const storedData = localStorage.getItem('_mobile_site_search');
  const value = storedData ? JSON.parse(storedData) : [];
  let newHistory = [searchValue.value, ...value];
  if (newHistory.length > 13) {
    newHistory = newHistory.slice(0, 13);
  }
  localStorage.setItem('_mobile_site_search', JSON.stringify(newHistory));
  $router.push({ path: '/searchDetail', query: { keyword: searchValue.value } });
};

const onTagClick = (props: string) => {
  $router.push({ path: '/searchDetail', query: { keyword: props } });
};

const onBackIconClick = () => {
  $router.go(-1);
};
const searchRef = ref<HTMLInputElement | null>(null);
const loadData = async () => {
  const storedData = localStorage.getItem('_mobile_site_search');
  // 搜索历史没有接口 后端叫存本地
  searchHistory.value = storedData ? JSON.parse(storedData) : [];
  searchRef.value?.focus();
};
onMounted(() => {
  loadData();
});
</script>
<template>
  <div class="home_search">
    <svg-icon @click="onBackIconClick" icon-class="left" size="1.1em" />
    <van-search
      v-model="searchValue"
      @search="onSearchClick"
      ref="searchRef"
      shape="round"
      placeholder="请输入搜索关键词"
    />
  </div>
  <div class="search-title">搜索历史</div>
  <div class="search-icon">
    <div
      v-for="(item, index) in searchHistory"
      :key="index"
      @click="onTagClick(item)"
      class="search-tag"
    >
      {{ item }}
    </div>
  </div>
</template>

<style scoped lang="scss">
.home_search {
  width: 100%;
  height: 49px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #f6f6f6;
  background: white;

  .van-search {
    width: 100%;
    height: 100%;
    padding-left: 8px;
  }
}

.search-title {
  width: 100%;
  height: 22px;
  line-height: 22px;
  margin: 10px 0 8px 0;
  padding: 0 16px;
  font-size: 15px;
  font-weight: 500;
  color: #454545;
}

.search-icon {
  width: 100%;
  min-height: 100px;
  padding: 0 16px;
  display: flex;
  flex-wrap: wrap;

  .search-tag {
    min-width: 64px;
    height: 34px;
    font-size: 12px;
    font-weight: 400;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 8px;
    margin: 0 8px 8px 8px;
    gap: 10px;
    border-radius: 20px;
    border: 1px solid #ebebeb;
    color: #787878;
  }
}
</style>
